package com.chinaunicom.sh.oss.antenna.code;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;

/**
 * 将生成的源码写入文件中<br/>
 * 
 * @author liuchengbiao
 *
 */
public class GenerateFileUtil {

	/** 基目录，生成的文件会在该目录下面形成，entity、dao、service、impl、web */
	public static  String baseFileDir = "/Users/liuchengbiao/Downloads/code2/";

	public static void writeToFile(String code) {
		BufferedWriter bw = null;
		try {
			String path = parsePackagePath(code);
			String fileName = parseFileName(code);
			File file = new File(path);
			file.mkdirs();

			File javaFile = new File(path + "/" + fileName + ".java");
			bw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(javaFile), "utf-8"));
			bw.write(code);
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (bw != null) {
				try {
					bw.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
	}

	/**
	 * 从源码中解析类名 作为文件名称<br/>
	 * 
	 * @param code
	 * @return
	 */
	public static String parseFileName(String code) {
		String str1 = "public class ";
		String str2 = "public interface ";
		int offSet = str1.length();
		int start = code.indexOf(str1);
		if (start < 0) {
			// 不存在，可能是接口
			start = code.indexOf(str2);
			offSet = str2.length();
		}
		// 截取
		int end = code.indexOf(" ", offSet + start);

		String fileName = code.substring(start + offSet, end);
		return fileName;
	}

	/**
	 * 从源码中解析出文件所在路径<br/>
	 * 
	 * @param code
	 * @return
	 */
	public static String parsePackagePath(String code) {
		int start = code.indexOf("package");
		if (start < 0) {
			System.out.println("无包名...");
			return "";
		}
		int end = code.indexOf(";", start);

		String packageName = code.substring(start + "package".length(), end).trim();

		return baseFileDir + packageName.replaceAll("\\.", "/");
	}

	public static void main(String[] args) {
		StringBuffer sb = new StringBuffer("");
		sb.append("package com.xiaoka.test.code;\n");
		sb.append("@Controller\n");
		sb.append("public class CamelvRouteLinkController extends BaseController {");
		String fileName = parseFileName(sb.toString());
		System.out.println("文件名" + fileName + ".java");
		String path = parsePackagePath(sb.toString());
		System.out.println("文件路径:" + path);
		File file = new File(path);
		file.mkdirs();
	}
}
